﻿using Autofac;
using Developer.Core.FrameWork.EventBus.EventHandling;
using Developer.Core.FrameWork.EventBus.Option;
using Developer.Core.FrameWork.EventBus.Service;
using Developer.Core.FrameWork.EventBus.SubscriptionManager.MemoryEventBus;
using Developer.Core.FrameWork.EventBus.SubscriptionManager.RabbitMQEventBus;
using Developer.Core.FrameWork.GlobalVar;
using Developer.Core.FrameWork.HelpFile;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;

namespace Developer.Core.FrameWork.EventBus.Extensions
{
    /// <summary>
    /// 事件总线扩展类
    /// </summary>
    public static class EventBusExtensions
    {
        public static void AddEventBusSerivce(this IServiceCollection services)
        {
            if (services == null)
                throw new ArgumentNullException(nameof(services));

            EventBusOption eoption = Appsettings.app<EventBusOption>("EventBus");
            RabbitMqOption roption = Appsettings.app<RabbitMqOption>("RabbitMQ");

            // 是否开启事件总线
            if (GlobalVars.EventBus)
            {
                services.AddSingleton<IEventBusSubscriptionsManager, InMemoryEventBusSubscriptionsManager>();
                services.AddTransient<DeveloperDeletedIntegrationEventHandler>();

                services.AddSingleton<IEventBus, EventBusRabbitMQ>(sp =>
                {
                    var rabbitMQConnection = sp.GetRequiredService<IRabbitMQConnection>();
                    var iLifeTimeScope = sp.GetRequiredService<ILifetimeScope>();
                    var logger = sp.GetRequiredService<ILogger<EventBusRabbitMQ>>();

                    var eventBusSubscriptionsManager = sp.GetRequiredService<IEventBusSubscriptionsManager>();

                    var retryCount = 5;
                    if (roption.RetryCount > 0)
                        retryCount = roption.RetryCount;

                    return new EventBusRabbitMQ(rabbitMQConnection, logger, iLifeTimeScope, eventBusSubscriptionsManager, eoption.SubscriptionClientName, retryCount);
                });

            }
        }

        public static void ConfigureEventBus(this IApplicationBuilder app)
        { 
            // 是否开启事件总线
            if (GlobalVars.EventBus)
            {
                var eventBus = app.ApplicationServices.GetService<IEventBus>();

                eventBus.Subscribe<DeveloperDeletedIntegrationEvent, DeveloperDeletedIntegrationEventHandler>();
            }
        }
    }
}
